import React, { FC, useCallback, useContext, useState } from 'react';
import { View, Text, Input } from '@tarojs/components';
import { styled } from 'linaria/react';
import { useClassName } from '@/utils/index';
import { ChagePersonalInfoContext } from '../ChagePersonalInfoContext';
import { apiGetChageNickName } from '@/pages/_server/_api/ChagePersonalInfo/apiGetChageNickName';
import JYInput from '@/components/JYInput/JYInput';
import Taro from '@tarojs/taro';
import Header from '../_components/Header/Header';

export interface IProps extends ICompProps {}
ChangeNickName.defaultProps = {} as Partial<IProps>;
function ChangeNickName(props: IProps) {
    const { className, style } = props;
    const localClassName = useClassName('ChangeNickName', className);
    const { userInfo, getUserInfo, setShowComponent } = useContext(ChagePersonalInfoContext);
    const [isChangeName, setIsChangeName] = useState<boolean>(false);
    const [newNickName, setNewNickName] = useState<string>('');
    const change = useCallback(
        (val) => {
            if (val === userInfo.nickName) return setIsChangeName(false);
            setNewNickName(val);
            return setIsChangeName(true);
        },
        [userInfo.nickName]
    );
    const confirm = useCallback(async () => {
        if (!isChangeName) return;
        const res = await apiGetChageNickName(newNickName);
        if (!res) return;
        const response = getUserInfo();
        if (!response)
            return Taro.showToast({
                title: '获取信息失败',
                icon: 'none',
                duration: 2000,
            });
        setShowComponent('BaseInfo');
        Taro.showToast({
            title: '修改成功',
            icon: 'none',
            duration: 2000,
        });
    }, [getUserInfo, isChangeName, newNickName, setShowComponent]);
    const cancel = useCallback(() => {
        setShowComponent('BaseInfo');
    }, [setShowComponent]);
    return (
        <RootView className={localClassName} style={style}>
            <Header isActiveConfirmBtn={isChangeName} cancel={cancel} confirm={confirm}></Header>
            <JYInput onChange={(val) => change(val)} value={userInfo.nickName}></JYInput>
        </RootView>
    );
}
export default React.memo(ChangeNickName as FC<IProps>);
const RootView = styled(View)`
    &.ChangeNickName {
        padding: 40px;
    }
`;
